package com.tang.common.async;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tang.common.constant.BusinessConstant;
import com.tang.module.system.entity.InterfaceLimit;
import com.tang.module.system.entity.User;
import com.tang.module.system.mapper.InterfaceLimitMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 异步执行接口限制相关方法
 * @author tang
 * @date 2022/1/21 16:14
 */
@Slf4j
@Component
public class LogInterfaceAsync {


    @Resource
    private InterfaceLimitMapper interfaceLimitMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 异步更新数据库中用户接口访问次数
     * @param user 用户
     * @param execute redis脚本执行状态
     * @param type 接口类型
     */
    @Async
    public void updateDatabase(User user, Integer type,Integer execute){
        //如果redis中无该用户的信息
        if (execute == -2){
            InterfaceLimit interfaceLimit = interfaceLimitMapper.selectOne(Wrappers.<InterfaceLimit>lambdaQuery().
                    eq(InterfaceLimit::getUserId, user.getId()).
                    eq(InterfaceLimit::getInterfaceType, type));
            //不为null，说明不为新用户，可能的原因是缓存没更新,这里直接更新缓存
            if (interfaceLimit != null){
                redisTemplate.opsForZSet().add(BusinessConstant.INTERFACE_RESTRICTION_FREQUENCY,interfaceLimit.getUserId() + "-"+ interfaceLimit.getInterfaceType(),interfaceLimit.getRemainingTimes());
            }
            return;
        }
       interfaceLimitMapper.updateTimes(user.getId(),type);
    }

}
